/* typehints:start */
import { People } from "../../people";
import { Goods } from "../../goods/goods";
import { Npc } from "../../npcs/npc";
/* typehints:end */

import { getObjectType, makeDiv } from "../../../core/utils/utils";
import { BaseHUDPart } from "../base_hud_part";
import { DynamicDom } from "../dynamic_dom";
import { SelectBtnGroup } from "../select_btn_group";
import { elementDefine } from "../../defines/element_define";
import { attrDefine } from "../../defines/attr_define";
import { RaceDefine } from "../../defines/race_define";
import { FormElementCheckbox, FormElementInput } from "../../../core/utils/modal_dialog_form";
import { MoneyDefine } from "../../defines/money_define";
import { getTimeToDay } from "../../time";
import { globalConfig } from "../../../config/global";
import { createLogger } from "../../../core/utils/logging";

const logger = createLogger('game/huds/parts/shop_board')

export class HUDShopBoard extends BaseHUDPart{
  constructor(root){
    super(root);
  }

  createElements(parent){
    this.element = makeDiv(
			parent,
			"shop_board",
			["remove", 'alert_board'],
			`
      <div class="screen"></div>
      <div class="close-btn"><img src="res/ui/icons/close.svg" /></div>
      <div class="content">
        <div class="btn-group">
        </div>
        <div class="wrapper">
          <div class="page buy-page">
            <div class="goods"></div>
          </div>
          <div class="page sold-page">
            <div class="goods"></div>
          </div>
        </div>
      </div>
    `
		);
  }
  
  initialize(){
    this.domAttach = new DynamicDom(this.root, this.element);

    this.bindCloseBtn();
  }

  bindCloseBtn(){
    let screen = this.element.querySelector('.screen');

    this.trackClicks(screen, this.handleHide.bind(this), {
      applyCssClass: ''
    });
  }

  handleHide(){
    this.domAttach.internalDetach(true);
  }

  /**
   * 
   * @param {Npc} npc 
   */
  handleShow(npc){
    this.domAttach.internalAttach();
    this.npc = npc;

    if(!this.selectBtns){
      this.selectBtns = new SelectBtnGroup(this.root, this.element.querySelector('.content'), '.btn-group', [
        {
          text: npc.getName() + '的小店',
          page: '.wrapper|buy-page',
          active: true,
        },
        {
          text: '出售',
          page: '.wrapper|sold-page',
        },
      ]);
    } else {
      this.selectBtns.setActive();
    }

    this.renderItems();
    this.renderPlayerItems();
  }

  renderItems(){
    let itemsParent = this.element.querySelector('.wrapper .buy-page .goods');
    itemsParent.innerHTML = '';
		let backdrop = this.npc.backdropDefine()(this);

    this.items = this.npc.attr.backdropShops.map(item => {
      let good =  this.root.worldMap.getGood(item.key, null, {
        num: item.num,
        ...(item.data || {})
      });

      if(item.id){
        let shop = backdrop.shops.find(shop => shop.id == item.id);
        if(shop){
          good.buyTip = shop.buyTip;
          good.show = shop.show;
          good.buy = shop.buy;
        }
      } else if(item.show || item.buy) {
        logger.warn(`虽然你为商品添加了显示、购买等判定功能，但是你没有为其添加id，商品: `, item);
      }

      return good;
    });

    this.items.map((item, index) => {
      let num = item.num;
      let itemPrice = item.getPrice();
      if(item.show && !item.show()) return;

      let dom = makeDiv(itemsParent, '', ['item', 'styledButton', item.getLevel()], `
        ${item.getTitle()}
        <p class="price">
          <img src="res/ui/icons/${itemPrice.type}.png" />
        ${itemPrice.price}</p>
        <span class="num">${!num ? '已告罄' : num == 1 ? '' : 'x' + num}</span>
      `);

      this.trackLongPressAndClick(dom, () => {
        this.root.hud.parts.goodsBoard.handleShowGoodsBoard(item, ['属性']);
      }, () => {
        if(!num){
          this.root.gameState.dialogs.showWarning('无法购买', 
            `该商品已经卖光了，请等待约购买时间后${getTimeToDay(this.npc.getShopUpdateTime())}天再来吧`)
        } else {
          if(item.buy && !item.buy()){
            this.root.gameState.dialogs.showWarning('无法购买', item.buyTip || '购买这样物品需要达成一些条件');
            return;
          }
          this.buyItem(item, index, itemPrice, num);
        }
      });
    })
  }

  buyItem(item, index, itemPrice, num){
    let numItem = new FormElementInput({
      id: 'num',
      label: '数量',
      defaultValue: num,
      validator: text => text > 0 && !isNaN(text) && text <= num
    })

    let { ok } = this.root.gameState.dialogs.showForm({
      title: '购买',
      desc: '单价: $' + itemPrice.price,
      formElements: [numItem],
    });

    ok.add(() => {
      let price = numItem.getValue() * itemPrice.price;
      let commodity = `<${item.getTitle()}>x${numItem.getValue()}`;
      let { ok } = this.root.gameState.dialogs.showInfo('确认商品', 
        `你确认购买${commodity}吗，总价：$${price}`,
        ['cancel:bad:取消', 'ok:success:确认']
      );
      
      ok.add(() => {
        let playerMoney = this.root.mainPlayer.data[itemPrice.type];

        if(playerMoney - price < 0){
          this.root.gameState.dialogs.showWarning('购买失败', `你无法购买。你只有${playerMoney}${MoneyDefine[itemPrice.type].text}`);
          return;
        }

        if(!this.root.backdrop.getGoodAndPut(item.key, {
          ...item.attr.data,
          num: numItem.getValue()
        })) return;

        this.npc.saveNpcData((peopleAttr, npcAttr) => {
          npcAttr.backdropShops.map((item, npcIndex) => {
            if(npcIndex == index) item.num -= numItem.getValue();
          })
          npcAttr.shopOnlyItem.push(item.key); 
        })

        this.root.mainPlayer.data[itemPrice.type] -= price;

        this.renderItems();
        this.root.savePlayerData();
      })
    })
  }

  renderPlayerItems(){
    let items = this.root.backdrop.getExistsGoods();
    let itemsParent = this.element.querySelector('.sold-page .goods')
    itemsParent.innerHTML = '';

    if(items.length > 0){
      items.map(item => {
        let num = item.num || 1;
        let itemPrice = item.getPrice();
        let specialDiscount = Object.keys(this.npc.getShopSpecialDiscount()).find(key => key == item.key);
        let discount = specialDiscount ? this.npc.getShopSpecialDiscount()[specialDiscount] : globalConfig.soldDiscount;
        itemPrice.price *= discount;

        let dom = makeDiv(itemsParent, '', ['item', 'styledButton', item.getLevel()], `
          <p>${item.getTitle()}</p>
          <p class="price">
            <img src="res/ui/icons/${itemPrice.type}.png" />
          ${itemPrice.price}</p>
          <span class="num">${num == 1 ? '' : 'x' + num}</span>
        `)

        this.trackClicks(dom, () => {
          this.soldItem(item, itemPrice);
        });
      })
    } else {
      itemsParent.innerHTML = '<p>没有任何物品</p>'
    }
  }

  soldItem(item, itemPrice){
    let numItem = new FormElementInput({
      id: 'num',
      label: '数量',
      defaultValue: item.num,
      validator: text => text > 0 && !isNaN(text) && text <= item.num
    })

    let { ok } = this.root.gameState.dialogs.showForm({
      title: '出售',
      desc: '单价: $' + itemPrice.price,
      formElements: [numItem],
    });

    ok.add(() => {
      let price = numItem.getValue() * itemPrice.price;
      let commodity = `<${item.getTitle()}>x${numItem.getValue()}`;
      let { ok } = this.root.gameState.dialogs.showInfo('确认商品', 
        `你确认出售${commodity}吗，总价：$${price}`,
        ['cancel:bad:取消', 'ok:success:确认']
      );
      
      ok.add(() => {
        this.root.backdrop.consume(item.backpackId, numItem.getValue());
        this.root.backdrop.playerGetMoney(itemPrice.type, price);

        this.renderPlayerItems();
        this.root.savePlayerData();
      })
    })
  }
}